<?php
/**
 * author:zhihong.yin
 * 临时表内容入bk资源库
 */
error_reporting(0);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load("ns_core.m_pinyin");
define('CP_ID','jycm');
define('SP_ID','jscn_bkzx');
class message extends \ns_model\message\message_explain
{
    //db实例
    private $db;

    private $cp_id;

    private $sp_id;

    public function  __construct()
    {
        $this->db = m_config::get_dc()->db();
        $this->cp_id = CP_ID;
        $this->sp_id = SP_ID;
    }

    public function run()
    {
        $this->returnMsg('单集入库开始');
        //单集  nns_index = 0
        $this->init_simple_set();

        $this->returnMsg('单集入库结束并开始多集入库');

        //多集  nns_index >=1
        $this->init_multi_set();
        $this->returnMsg('多集入库结束');
    }

    private  function my_str_replace($str='')
    {
        $str = str_replace(' ', '', trim($str));
        if(strlen($str)<1)
        {
            return $str;
        }
        $str = str_replace('-', '', $str);
        if(strlen($str)<1)
        {
            return $str;
        }
        $str = str_replace(array(',','，','|','#','*'), '/', $str);
        $str = str_replace(' ', '', trim($str));
        return $str;
    }

    public function do_serice($arr_series)
    {
        $pinyin = m_pinyin::get_pinyin_letter($arr_series['nns_name']);
        $view_type = $arr_series['nns_index'] >1 ? '1' : '0';
        $add_series = array(
            'base_info' => array(
                'nns_name' => $arr_series['nns_name'],
                'nns_view_type' => $view_type,
                'nns_org_type' => '0',
                'nns_tag' => '26,',
                'nns_director' => $this->my_str_replace($arr_series['nns_director']),
                'nns_actor' => $this->my_str_replace($arr_series['nns_actor']),
                'nns_show_time' => (strlen($arr_series['nns_year']) > 0 && (int)$arr_series['nns_year'] > 1970 && (int)$arr_series['nns_year'] < 2020) ? (int)$arr_series['nns_year'] : date("Y"),
                'nns_view_len' => 0,
                'nns_all_index' => $arr_series['nns_index'],
                'nns_new_index' => $arr_series['nns_index']-1,
                'nns_area' => $this->my_str_replace($arr_series['nns_area']),
                'nns_image0' =>  '',
                'nns_image1' => '',
                'nns_image2' => '',
                'nns_image3' => '',
                'nns_image4' => '',
                'nns_image5' => '',
                'nns_summary' => '',
                'nns_remark' => '',
                'nns_category_id' => $arr_series['nns_category_id'],
                'nns_play_count' => '0',
                'nns_score_total' => '0',
                'nns_score_count' => '0',
                'nns_point' => '0',
                'nns_copyright_date' => (strlen($arr_series['nns_year']) > 0 && (int)$arr_series['nns_year'] > 1970 && (int)$arr_series['nns_year'] < 2020) ? (int)$arr_series['nns_year'] : date("Y"),
                'nns_asset_import_id' => $arr_series['nns_video_import_id'],
                'nns_pinyin' => $pinyin,
                'nns_pinyin_length' => strlen($pinyin),
                'nns_alias_name' => $arr_series['nns_name'],
                'nns_eng_name' => '',
                'nns_language' => '',
                'nns_text_lang' => '',
                'nns_producer' => '',
                'nns_screenwriter' => '',
                'nns_play_role' => '',
                'nns_copyright_range' => '',
                'nns_vod_part' => '',
                'nns_keyword' => '',
                'nns_import_source' => evn::get("project"),
                'nns_kind' => '',
                'nns_copyright' => '',
                'nns_clarity' => '',
                'nns_image_v' => '',
                'nns_image_s' => '',
                'nns_image_h' => '',
                'nns_cp_id' => $arr_series['nns_cp_id'],
                'nns_conf_info' => '',
                'nns_ext_url' => '',
            ), //基本信息（存储于nns_vod表中）
            'ex_info' => array(
                'svc_item_id' => '',
                'month_clicks' => '',
                'week_clicks' => '',
                'base_id' => '',
                'asset_path' => '',
                'ex_tag' => '',
                'full_spell' => '',
                'awards' => '',
                'year' => '',
                'play_time' => '',
                'channel' => '',
                'first_spell' => '',
            ), //扩展信息（存储于nns_vod_ex表中）
        );
        //字段待修改4-14
        return $this->vod_action('add', $add_series);
    }

    public function do_index($arr_index)
    {
        $add_index = array(
            'base_info' => array(
                'nns_name' => $arr_index['nns_name'],
                'nns_index' => $arr_index['nns_index']-1,
                'nns_time_len' => '',
                'nns_summary' => '',
                'nns_image' => '',
                'nns_play_count' => 0,
                'nns_score_total' => 0,
                'nns_score_count' => 0,
                'nns_video_import_id' => $arr_index['nns_video_import_id'],
                'nns_import_id' => $arr_index['nns_index_import_id'],
                'nns_import_source' => evn::get("project"),

                'nns_director' => $this->my_str_replace($arr_index['nns_director']),
                'nns_actor' => $this->my_str_replace($arr_index['nns_actor']),
                'nns_release_time' => (strlen($arr_index['nns_year']) > 0 && (int)$arr_index['nns_year'] > 1970 && (int)$arr_index['nns_year'] < 2020) ? (int)$arr_index['nns_year'] : date("Y"),
                'nns_update_time' => date("Y-m-d"),
                'nns_watch_focus' => '',
                'nns_cp_id' => $arr_index['nns_cp_id'],
                'nns_conf_info' => '',
                'nns_ext_url' => '',
            ),
            'ex_info' => array(
                'isintact' => '',
                'subordinate_name' => '',
                'initials' => '',
                'publisher' => '',
                'first_spell' => '',
                'caption_language' => '',
                'language' => '',
                'region' => '',
                'adaptor' => '',
                'sreach_key' => '',
                'event_tag' => '',
                'year' => '',
                'sort_name' => '',
            ),
        );
        //分集注入
        return $this->index_action('add', $add_index);
    }

    public function do_media($arr_media)
    {
        $add_media = array(
            'base_info' => array(
                'nns_name' => $arr_media['nns_name'],
                'nns_type' => 1,
                'nns_url' => '',
                'nns_tag' => '26,',
                'nns_mode' => '',
                'nns_kbps' => '',
                'nns_content_id' => $arr_media['nns_assetid'],
                'nns_content_state' => 0,
                'nns_filetype' => 'ts',
                'nns_play_count' => '0',
                'nns_score_total' => '0',
                'nns_score_count' => '0',
                'nns_video_import_id' => $arr_media['nns_video_import_id'],
                'nns_index_import_id' => $arr_media['nns_index_import_id'],
                'nns_import_id' => $arr_media['nns_media_import_id'],
                'nns_import_source' => evn::get("project"),
                'nns_dimensions' => '2D',
                'nns_ext_url' => '',
                'nns_file_size' => 0,
                'nns_file_time_len' => 0,
                'nns_file_frame_rate' => 0,
                'nns_file_resolution' => 0,
                'nns_cp_id' => $arr_media['nns_cp_id'],
                'nns_ext_info' => '',
                'nns_drm_enabled' =>  0,
                'nns_drm_encrypt_solution' => '',
                'nns_drm_ext_info' => '',
                'nns_domain' => 0,
                'nns_media_type' => 1,
                'nns_original_live_id' => '',
                'nns_start_time' => '',
                'nns_media_service' => 'HTTP',
                'nns_conf_info' => '',
                'nns_encode_flag' => 0,
                'nns_live_to_media' => '',
                'nns_media_service_type' => '',
            ),
            'ex_info' => array(
                'file_hash' => '',
                'file_width' => '',
                'file_height' => '',
                'file_scale' => '',
                'file_coding' => '',
            ),
        );
        return  $this->media_action('add', $add_media);
    }

    //创建栏目
    private function do_category($category_name)
    {
        $do_category = array(
            'base_info'=>array(
                'nns_name'=>$category_name,   //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_import_category_id'=>'', //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_cp_id'=>$this->cp_id,
                'nns_import_parent_category_id'=>'',
                'nns_video_type'=>'0',  //媒资类型  0 点播 | 1 直播
            ),
        );
        $result_cate = $this->category_action('add', $do_category);

        if($result_cate['ret'] !=0 || !isset($result_cate['data_info']['base_info']['nns_id']) || strlen($result_cate['data_info']['base_info']['nns_id']) <1)
        {
            $this->returnMsg("创建栏目{$category_name}失败",'die');
        }
        return $result_cate;
    }

    //处理单集,单集的主媒资-分集-片源的注入id都为临时表的nns_assetid
    public function init_simple_set()
    {
        //创建单集栏目
        $result_cate = $this->do_category('单集');
        while(true)
        {
            $sql="SELECT * FROM `nns_asset_source_incre_group` 
                                where nns_state='0'  
                                and nns_index = 0
                                ORDER BY `nns_name`desc,
                                `nns_index` desc
                                LIMIT 0,1000";
            $result = nl_query_by_db($sql, $this->db);

            if( empty($result) || !is_array($result) )
            {
                break;
            }
            foreach ($result as $value)
            {
                //主媒资名字为空  nns_state 2
                if(strlen($value['nns_name']) <1)
                {
                    nl_execute_by_db("update nns_asset_source_incre_group set nns_state='2' where nns_id='{$value['nns_id']}'", $this->db);
                    continue;
                }

                $value['nns_category_id'] = $result_cate['data_info']['base_info']['nns_id'];


                $value['nns_index'] = (int)$value['nns_index'] <1 ? 1 : (int)$value['nns_index'];
                $value['nns_cp_id']= $this->cp_id;

                $arr_series = $value;
                $arr_series['nns_video_import_id'] = $value['nns_assetid'];
                $this->do_serice($arr_series);
                $arr_index = $arr_series;
                $arr_index['nns_name'] = $arr_index['nns_name']."  第{$value['nns_index']}集";
                $arr_index['nns_index_import_id'] = $value['nns_assetid'];
                $this->do_index($arr_index);
                $arr_media = $arr_index;
                $arr_media['nns_name'] = $arr_index['nns_name']."{$value['nns_id']}";
                $arr_media['nns_media_import_id'] = $value['nns_assetid'];
                $this->do_media($arr_media);
                //改变分组后的状态
                nl_execute_by_db("update nns_asset_source_incre_group set nns_state='1' where nns_id='{$value['nns_id']}'",$this->db);

                //补充nns_asset_source_incre和nns_asset_source_incre_group表中主媒资id
                foreach( ['nns_asset_source_incre_group','nns_asset_source_incre'] as $table )
                {
                    $sql = "update {$table}  set nns_series_id = '{$value["nns_assetid"]}'  
                                                where nns_assetid = '{$value['nns_assetid']}'
                                                and (nns_series_id is null or length(nns_series_id) = 0)";
                    nl_execute_by_db($sql,$this->db);
                }
            }
        }
    }


    //多集,主媒资注入id为md5（主媒资名称）,分集-片源注入id为原媒资表中nns_assetid,实现一对多关联
    public function init_multi_set()
    {
        //创建单集栏目
        $result_cate = $this->do_category('多集');
        while(true)
        {
            //每次从group取1000条初始状态为0的数据，直到取完为止，每次循环，状态为0的都在不断减少
            $sql="SELECT * FROM `nns_asset_source_incre_group` 
                                where nns_state='0'  
                                and nns_index > 0
                                ORDER BY `nns_name`desc,
                                `nns_index` desc
                                LIMIT 0,1000";
            $result = nl_query_by_db($sql, $this->db);
            if( empty($result) || !is_array($result) )
            {
                break;
            }
            $last_data = null;
            //获取同一个主媒资下集合数组
            foreach ($result as $value)
            {
                if(strlen($value['nns_name']) <1)
                {
                    nl_execute_by_db("update nns_asset_source_incre_group set nns_state='2' where nns_id='{$value['nns_id']}'", m_config::get_dc()->db());
                    continue;
                }

                $value['nns_index'] = (int)$value['nns_index'] <1 ? 1 : (int)$value['nns_index'];
                //分集的具体名称
                $extra_index_name = '';
                /**
                 * 多集中还要分情况判断
                 * 1.名字只有字母和数字，nns_index设为1
                 * 2.名字中含有第几季+数字的，用数字作分割，第一部分作为主媒资名称，第二部分作为分集名称
                 */

                if( strlen($value['nns_name']) == mb_strlen($value['nns_name']) )
                {
                    //1.全英文
                    $value['nns_index']=1;
                    $str_name = preg_replace("/0*{$value['nns_index']}/",'',$value['nns_name']);
                }
                else if( preg_match('/第\S+季(\d+)/',$value['nns_name'],$output))
                {
                    //2.含有第几季的,以第几季后面的数字进行分割
                    $arr_name = explode($output[1],$value['nns_name']);
                    $str_name = $arr_name[0];
                    $extra_index_name = $arr_name[1];
                }
//                else if($first_char = strpos($value['nns_name'],'《') === 0 && $value['nns_index']>1)
//                {
//                    //以《开头的，且集数至少为两集,其中的内容设为主媒资
//                    $second_char = strpos($value['nns_name'],'》');
//
//                    $str_name = substr($value['nns_name'],$first_char+3,$second_char-3);
//
//                    //分集名称部分
//                    $extra_index_name = str_replace("《{$str_name}》",'',$value['nns_name']);
//                }
                else
                {
                    //非特殊情况
                    $str_name = preg_replace("/0*{$value['nns_index']}/",'',$value['nns_name']);
                }
                if( empty($str_name))  var_dump($value);

                $value['nns_cp_id'] = $this->cp_id;
                $video_id = md5($str_name);

                //主媒资信息，名称-集数-注入id，以video_id作为标识
                if(!isset($last_data[$video_id]['video']))
                {
                    $video_value = $value;
                    $video_value['nns_name'] = $str_name;
                    $video_value['nns_index'] = (int)$value['nns_index'] <1 ? 1 : (int)$value['nns_index'];
                    $video_value['nns_video_import_id'] = $video_id;
                    $last_data[$video_id]['video'] = $video_value;
                }
                //group中每条记录数据，同时作为主媒资，分集，片源的公共基本信息
                $index_value = $value;

                $index_value['nns_name'] = $str_name."  第{$index_value['nns_index']}集  {$extra_index_name}";
                $index_value['nns_index_import_id'] = $value['nns_assetid'];
                $index_value['nns_video_import_id'] = $video_id;
                $last_data[$video_id]['index'][$value['nns_index']] = $index_value;


                $media_value = $index_value;
                $media_value['nns_name'] = $media_value['nns_name']."_{$media_value['nns_id']}";
                $media_value['nns_media_import_id'] = $value['nns_assetid'];
                $last_data[$video_id]['media'][] = $media_value;
                $last_data[$video_id]['ids'][] = $value['nns_id'];

                //补充nns_asset_source_incre和nns_asset_source_incre_group表中主媒资id,已存在媒资注入id的不再更新
                foreach( ['nns_asset_source_incre_group','nns_asset_source_incre'] as $table )
                {
                    $sql = "update {$table} set nns_series_id = '{$video_id}'  
                                                where nns_assetid = '{$value["nns_assetid"]}'
                                                and (nns_series_id is null or length(nns_series_id) = 0 )";
                    nl_execute_by_db($sql,$this->db);
                }

            }
            if(!is_array($last_data) || empty($last_data))
            {
                continue;
            }

            foreach ($last_data as $in_key=>$in_value)
            {
                $in_value['video']['nns_category_id'] = $result_cate['data_info']['base_info']['nns_id'];
                $this->do_serice($in_value['video']);
                foreach ($in_value['index'] as $in_index_value)
                {
                    $this->do_index($in_index_value);
                }
                foreach ($in_value['media'] as $in_media_value)
                {
                    $this->do_media($in_media_value);
                }
                //注入资源库成功，状态置为1
                nl_execute_by_db("update nns_asset_source_incre_group set nns_state='1' where nns_id in('".implode("','", $in_value['ids'])."')", $this->db);

            }
        }
    }


    /**
     * @param $msg     脚本信息
     * @param null $type    信息类型   die 终止信息  |  其他  一般提示信息
     * 脚本执行信息
     */
    public function returnMsg($msg,$type = null)
    {
        if( is_string($msg) && !empty($msg))
        {
            echo str_pad($msg,50,'-',STR_PAD_BOTH).PHP_EOL;
            if($type == 'die')
            {
                echo str_pad('进程结束',50,'-',STR_PAD_BOTH).PHP_EOL;
                exit;
            }
        }
    }
}

$obj = new message();
$obj->run();